import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains

import time
class Grap():
    def __init__(self):
        self.service = Service(executable_path=r"C:\Program Files (x86)\Microsoft\Edge\Application\msedgedriver.exe")

        self.driver = webdriver.Edge()
        self.df = pd.DataFrame(columns=["id","title","score","star","year","duration","director","actors","vote"])
        self.df_save_path = "./data/nowplay.csv"
        self.sc_df = pd.DataFrame(columns=["rating","comment"])
        self.sc_save_path = "./data/shorts_comments.csv"


    def get_nowplaying(self):
        self.driver.get("https://movie.douban.com/cinema/nowplaying/leshan/")
        time.sleep(2)
        elements = self.driver.find_elements(By.XPATH,"//ul[@class='lists']/li[@class='list-item']")
        i=0
        for ele in elements:
            did = ele.get_attribute("id")
            dtitle = ele.get_attribute("data-title")
            dscore = ele.get_attribute("data-score")
            dstar = ele.get_attribute("data-star")
            dyaer = ele.get_attribute("data-release")
            ddura = ele.get_attribute("data-duration")
            ddirector =ele.get_attribute("data-director")
            dactors= ele.get_attribute("data-actors")
            dvote = ele.get_attribute("data-votecount")
            self.df.loc[i] = [did,dtitle,dscore,dstar,dyaer,ddura,ddirector,dactors,dvote]
            i=i+1
        self.df.to_csv(self.df_save_path,index=None)



    def get_short_comment(self):
        self.driver.get("https://movie.douban.com/subject/36653918/comments?status=P")
        a = 0
        while(a<1000):
            elements1 = self.driver.find_elements(By.XPATH, "//span[@class='short']")
            elements2 = self.driver.find_elements(By.XPATH, "//span[@class='comment-info']/span[contains(@class,'rating')]")

            for ele1,ele2 in zip(elements1,elements2):
                comment = ele1.text
                rating = ele2.get_attribute("title")
                self.sc_df.loc[a] = [rating,comment]
                a = a+1

            next_ele = self.driver.find_elements(By.XPATH,"//div[@id='paginator']/a")
            try:
                link = next_ele[2].get_attribute("href")
                self.driver.get(link)
            except:
                break

        self.sc_df.to_csv(self.sc_save_path, index=None)


    def count_ratings(self):
        # 检查数据框是否为空
        if self.sc_df.empty:
            print("请先运行 `get_short_comment()` 方法爬取数据。")
            return
        
        # 统计 `rating` 列中的星级数量
        rating_counts = self.sc_df['rating'].value_counts()
        print("星级统计结果：")
        print(rating_counts)
        return rating_counts

if __name__=="__main__":
    g = Grap()
    #g.get_nowplaying()
    g.get_short_comment()
    g.count_ratings()













